package com.msun.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.msun.dao.PlanDao;
import com.msun.entity.PageResult;
import com.msun.entity.QueryPageBean;
import com.msun.pojo.Plan;
import com.msun.service.PlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PlanService.class)
@Transactional
public class PlanServiceImpl implements PlanService {
    @Autowired
    PlanDao planDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage,pageSize);
        //select * from t_checkitem limit 0,10
        Page<Plan> page = planDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Plan> rows = page.getResult();
        return new PageResult(total,rows);

    }

    @Override
    public Plan findById(Integer id) {
        Plan plan= planDao.findById(id);
        return plan;
    }

    @Override
    public void add(Plan plan,Integer[] foodIds, Integer[] sportsIds) {
        Integer OrderId = plan.getId();

        Long count= planDao.findCountFoodById(OrderId);
        Long count1= planDao.findCountSportsById(OrderId);
        if(count >0){
            planDao.deleteFoodById(OrderId);
        }

        if(count1 >0){
            planDao.deleteSportsById(OrderId);
        }
        // 获取选中的food信息
        if(foodIds != null && foodIds.length > 0){
            for (Integer foodId : foodIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("orderId",plan.getId());
                map.put("foodId",foodId);
                // 添加food和订单的关联
                planDao.insertOrderIdAndFood(map);
            }
        }
        // 获取选中的sport信息
        if(sportsIds != null && sportsIds.length > 0){
            for (Integer sportsId : sportsIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("orderId",plan.getId());
                map.put("sportsId",sportsId);
                // 添加sport和订单的关联
                planDao.insertOrderIdAndSports(map);
            }
        }
    }
}
